package com.five.matebook.activity;


import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.view.Gravity;
import android.widget.EditText;

public class NewMatebookDialogFragment extends androidx.fragment.app.DialogFragment {

    private EditText editText;

    public interface DialogListener {
        void onTextEntered(String text);
    }

    private DialogListener listener;
    public NewMatebookDialogFragment(DialogListener listener) {
        this.listener = listener;
    }

    private volatile boolean mHasValue = false;
    @Override
    public androidx.appcompat.app.AlertDialog onCreateDialog(Bundle savedInstanceState) {
        editText = new EditText(getActivity());
        editText.setInputType(InputType.TYPE_CLASS_TEXT);
        editText.setGravity(Gravity.CENTER);
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(8)});

        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(getActivity());
        builder.setTitle("新建账本")
                .setView(editText)
                .setPositiveButton("新建", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mHasValue = true;
                        String text = editText.getText().toString();
                        listener.onTextEntered(text);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 取消按钮的点击事件
                        dismiss();
                        listener.onTextEntered(null);
                    }
                });

        return builder.create();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!mHasValue) {
            listener.onTextEntered(null);
        }
    }
}
